package com.guoqi.fingerdemo

import android.content.Context
import android.hardware.fingerprint.FingerprintManager
import android.os.Build
import android.os.Bundle
import android.support.v4.hardware.fingerprint.FingerprintManagerCompat
import android.support.v7.app.AppCompatActivity
import android.view.Gravity
import android.view.View
import android.widget.Toast
import com.orhanobut.dialogplus.DialogPlus
import com.orhanobut.dialogplus.ViewHolder
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.view_finger.view.*

class MainActivity : AppCompatActivity() {

    /**
     * 指纹识别
     */
    private var mFingerUtil: FingerUtil? = null
    private var mFingerListen: FingerprintManagerCompat.AuthenticationCallback? = null
    private lateinit var fingerView: View
    private lateinit var dialog: DialogPlus

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        if (checkFingerModule()) {
            btn_finger.setOnClickListener {
                // 检测是否需要初始化
                if (mFingerListen == null || mFingerUtil == null) {
                    //初始化指纹识别
                    initFinger()
                } else {
                    // 启动指纹识别
                    mFingerUtil?.startFingerListen(mFingerListen)
                    showFingerDialog()
                }
            }
        } else {
            btn_finger.setOnClickListener {
                Toast.makeText(this@MainActivity, "该设备不支持指纹识识别", Toast.LENGTH_SHORT).show()
            }
        }
    }


    private fun checkFingerModule(): Boolean {
        return try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                (getSystemService(Context.FINGERPRINT_SERVICE) as FingerprintManager).isHardwareDetected
            } else {
                false
            }
        } catch (e: Exception) {
            false
        }
    }

    /**
     * 初始化指纹模块
     */
    private fun initFinger() {
        mFingerListen = object : FingerprintManagerCompat.AuthenticationCallback() {

            /**
             * 指纹识别成功
             */
            override fun onAuthenticationSucceeded(result: FingerprintManagerCompat.AuthenticationResult?) {
                fingerView.tv_tip.text = "指纹识别成功"
                dialog.dismiss()
                Toast.makeText(this@MainActivity, "指纹识别成功", Toast.LENGTH_SHORT).show()
            }

            /**
             * 识别失败
             */
            override fun onAuthenticationFailed() {
                fingerView.tv_tip.text = "指纹不匹配"
            }

            /**
             * Msg监听
             * @param helpMsgId Msg码
             * @param helpString Msg文案
             */
            override fun onAuthenticationHelp(helpMsgId: Int, helpString: CharSequence?) {
                if (fingerView.tv_tip.tag != null && false == fingerView.tv_tip.tag as Boolean) {
                    return
                }
                when (helpMsgId) {
                    1001      // 等待按下手指
                    -> {
                        fingerView.tv_tip.text = "请验证指纹"
                    }
                    1002      // 手指按下
                    -> fingerView.tv_tip.text = "正在识别"
                    1003      // 手指抬起
                    -> {
                        fingerView.tv_tip.text = "手指抬起，请重新按下"
                    }
                }
            }

            /**
             * 多次指纹密码验证错误后，进入此方法；并且，不能短时间内调用指纹验证
             * @param errMsgId 错误码
             * @param errString 剩余禁用时间
             */
            override fun onAuthenticationError(errMsgId: Int, errString: CharSequence?) {
                when (errMsgId) {
                    5      // 可以进行识别
                    -> {
                        fingerView.tv_tip.tag = true
                    }
                    7      // 失败次数过多，禁用倒计时未结束
                    -> {
                        fingerView.tv_tip.text = errString
                        fingerView.tv_tip.tag = false
                    }
                }
            }
        }
        mFingerUtil = FingerUtil(this)
        mFingerUtil!!.startFingerListen(mFingerListen)
        showFingerDialog()
    }


    private fun showFingerDialog() {
        fingerView = View.inflate(this, R.layout.view_finger, null)
        dialog = DialogPlus.newDialog(this)
                .setContentHolder(ViewHolder(fingerView))
                .setGravity(Gravity.CENTER)
                .setInAnimation(R.anim.fade_in_center)//in动画
                .setOutAnimation(R.anim.fade_out_center)//out动画
                .setPadding(1, 1, 1, 1)
                .setMargin(100, 0, 100, 0)
                .setCancelable(false)
                .setExpanded(false)
                .create()
        dialog.show()

        fingerView.tv_cancel.setOnClickListener {
            dialog.dismiss()
        }
    }

    override fun onDestroy() {
        mFingerUtil?.stopsFingerListen()
        super.onDestroy()
    }
}
